package cn.alone.product.controller;

import cn.alone.basic.BusinessException;
import cn.alone.basic.util.AjaxResult;
import cn.alone.basic.util.LoginContext;
import cn.alone.basic.util.PageList;
import cn.alone.product.domain.Product;
import cn.alone.product.query.ProductQuery;
import cn.alone.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private IProductService productService;
    /**
     * 分页加高级查询
     * @param query
     * @return
     */
    @PostMapping
    public PageList<Product> queryPage(@RequestBody ProductQuery query){
        return productService.querpage(query);
    }

    /**
     * 上架
     * @param ids
     * @return
     */
    @PostMapping("/onsale")
    public AjaxResult onSale(@RequestBody List<Long> ids) {
        try {
            productService.onSale(ids);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("上架操作异常,请联系管理员");
        }
    }

    /**
     * 下架
     * @param ids
     * @return
     */
    @PostMapping("/offsale")
    public AjaxResult offSale(@RequestBody List<Long> ids) {
        try {
            productService.offSale(ids);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("下架操作异常,请联系管理员");
        }
    }

    /**
     * 新增服务
     * @param product
     * @param request
     * @return
     */
    @PutMapping("/save")
    public AjaxResult handle(@RequestBody Product product, HttpServletRequest request) {
        try {
            productService.handle(product, LoginContext.getCurrentLogininfo(request));
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("提交服务失败,稍后重试");
        }
    }
    @GetMapping("/{id}")
    public Product findById(@PathVariable("id") Long id){
        return productService.loadByIdDetail(id);
    }
}
